/**
 * Created by fangshufeng on 2018/2/28.
 */

import React from 'react'

import jsonFormat from  'json-format';
import MListView from './MListView'

import {Row, Button, Col, Input, Checkbox, Radio} from 'antd';

import  {ErrorModalAutoDismiss} from './AlertManage';

import MockHistory from './MockHistory'

const RadioButton = Radio.Button;
const RadioGroup = Radio.Group;


const KborderHeight = 700;

const {TextArea} = Input;

class OriginalListView extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            currentTimeStamp: null,
        }
    }

    cellDidClick = (index, item) => {
        this.props.itemDidClick(item);
        this.setState({currentTimeStamp: item.config.timestamp});
    };

    btnSubViews = (item) => {

        if (item.isMock === true) {

            if (item.status === 200) {
                return <div>
                    <span style={{color: 'blue', fontSize: 20}}>{item.mockTag} &nbsp;</span>{item.config.url}
                    {/*<span style={{color: 'blue', fontSize: 25}}>M &nbsp;</span>{item.config.timestamp}*/}
                </div>
            }
            return <div>
                <span style={{color: 'blue', fontSize: 20}}>{item.mockTag} &nbsp;</span> <span
                // style={{color: 'red', fontSize: 25}}>F &nbsp;</span>{item.config.timestamp}
                style={{color: 'red', fontSize: 20}}>F &nbsp;</span>{item.config.url}
            </div>
        }

        if (item.status === 200) {
            return <div>{item.config.url}</div>
            // return <div>{item.config.timestamp}</div>
        }

        return <div>
            {/*<span style={{color: 'red', fontSize: 25}}>F &nbsp;</span>{item.config.timestamp}*/}
            <span style={{color: 'red', fontSize: 25}}>F &nbsp;</span>{item.config.url}
        </div>
    };


    render() {

        const styleObj = {
            mainStyle: {
                marginTop: 20,
                marginRight: 10,
                height: KborderHeight * 0.5
            },
            titleStyle: {
                color: "#92cdec"
            },
            cleanBtnStyle: {
                color: '#92cdec',
                borderColor: '#92cdec',
                height: 20,
                fontSize: 8
            }
        };


        return <div style={styleObj.mainStyle}>

            <Row type='flex' justify='space-between'>
                <div style={styleObj.titleStyle}>原始请求</div>
                <Button style={styleObj.cleanBtnStyle} onClick={() => this.props.clearClick() }>清空</Button>
            </Row>

            <MListView
                style={{height: KborderHeight * 0.5 * 0.85}}
                dataSource={this.props.dataSource}
                renderItem={(item, index) => {
                    return <div key={index}
                                style={{
                                    backgroundColor: this.state.currentTimeStamp === item.config.timestamp ? '#e6f7ff' : 'white',
                                    height: 44,
                                }}>
                        <Button
                            style={{
                                fontSize: 12,
                                borderColor: 'rgba(0,0,0,0)',
                                backgroundColor: 'rgba(0,0,0,0)',
                                height: 44,
                                color: this.state.currentTimeStamp === item.config.timestamp ? '#1890ff' : 'rgba(0, 0, 0, 0.65)'
                            }}
                            onClick={() => this.cellDidClick(index, item)}>
                            {this.btnSubViews(item)}
                        </Button>
                    </div>
                }
                }
            />
        </div>
    }
}


class CenterView extends React.Component {

    responDefaultValue = () => {
        try {
            return jsonFormat(this.props.dataValue.data, {
                type: 'space',
                size: 2
            });
        } catch (e) {
            try {
                return this.props.dataValue.data;
            } catch (e) {
                return '';
            }
        }

    };

    mockValue = () => {
        try {
            let value = this.refs.result.textAreaRef.value;
            // JSON.parse(value);
            return JSON.parse(value)
        } catch (e) {
            return undefined;
        }

    };

    textView = () => {

        // let divKey = ''
        // try {
        //     divKey = this.props.dataValue.config.url;
        // } catch (e) {
        //     divKey = '';
        //
        // }this.props.texareaReadonly

        if (this.props.texareaReadonly) {
            return <div key={(new Date()).valueOf()}>
                            <TextArea
                                ref="result"
                                type="text"
                                defaultValue={this.responDefaultValue()}
                                autosize={false}
                                style={{
                                    height: KborderHeight - 70,
                                    marginLeft: -10,
                                    marginTop: 10
                                }}
                                readonly="readonly"
                            />
            </div>
        }
        return <div key={(new Date()).valueOf()}>
                            <TextArea
                                ref="result"
                                type="text"
                                defaultValue={this.responDefaultValue()}
                                autosize={false}
                                style={{
                                    height: KborderHeight - 70,
                                    marginLeft: -10,
                                    marginTop: 10
                                }}

                            />
        </div>
    };

    render() {
        return <Row>
            <Col span={1}>
                <div style={{
                    marginTop: 10,
                    width: 3,
                    height: KborderHeight - 20,
                    backgroundColor: '#92cdec'
                }}/>
            </Col>

            <Col span={23} style={{
                marginTop: 15
            }}>
                            <span style={{
                                color: '#92cdec'
                            }}>请求答复
                            </span>

                <Button style={{display: 'inline-block', marginLeft: 10, height: 30}}
                        onClick={() => {
                            this.props.mockClick(this.props.dataValue)
                        }}
                        disabled={this.props.btnDisabled}>新增Mock数据-></Button>

                {this.textView()}
            </Col>
        </Row>
    }
}

class RightView extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            size: 'default',
            currentText: null
        }
    }

    render() {
        const {size} = this.state;

        const StyleObj = {
            btnStyle: {
                height: 30
            }
        };
        return <Row type='flex' justify='space-between'>
            <Col span={1}>
                <div style={{
                    marginTop: 10,
                    width: 3,
                    height: KborderHeight - 20,
                    backgroundColor: '#92cdec'
                }}/>
            </Col>

            <Col span={23} style={{marginTop: 10}}>
                <div style={{
                    color: '#92cdec',
                    textAlign: 'center',
                    fontFamily: 'cursive'
                }}>{this.props.method} &nbsp; {this.props.timeValue}
                </div>

                <div style={{textAlign: 'center', marginTop: 10}}>
                    <RadioGroup value={this.props.segmentValue} size="small" onChange={(e) => this.props.tabClick(e)}>
                        <RadioButton value="url" style={StyleObj.btnStyle}>请求地址</RadioButton>
                        <RadioButton value="data" style={StyleObj.btnStyle}>请求参数</RadioButton>
                        <RadioButton value="headers" style={StyleObj.btnStyle}>请求头</RadioButton>
                    </RadioGroup>
                </div>

                <TextArea
                    ref="result"
                    type="text"
                    value={this.props.currentText}
                    autosize={false}
                    style={{
                        height: KborderHeight - 90,
                        marginTop: 10
                    }}
                />

            </Col>
        </Row>;
    }
}
export  default  class BodyView extends React.Component {

    constructor(props) {
        super(props);

        this.state = {
            centerValue: null,
            mockDic: {},
            addMockBtnDisabled: false,
            texareaReadonly: true,

            openKey: [],
            defaultSelectedKey: null,

            otherInfoKey: 'url'


        };
    }

    dedupe = (array) => {

        return Array.from(new Set(array));
    };

    render() {
        return <div style={{
            marginLeft: 20,
            marginRight: 20
        }}>
            {/*线条*/}
            <div style={{
                height: 3,
                backgroundColor: '#92cdec'
            }}/>

            <Row>
                {/*左*/}
                <Col span={6}>

                    <OriginalListView
                        dataSource={this.props.dataSource}
                        clearClick={() => {
                            this.props.clearClick();
                            this.setState({centerValue: null})
                        }}
                        itemDidClick={(value) => {
                            this.setState({
                                centerValue: {...value},
                                addMockBtnDisabled: false,
                                texareaReadonly: true,
                                otherInfoKey: 'url'
                            })
                        }
                        }/>

                    <MockHistory dataDic={this.state.mockDic}
                                 defaultOpenKey={this.state.openKey}
                                 defaultSelectedKey={this.state.defaultSelectedKey}
                                 checkboxAction={(checked, groupKey, groupIndex, mockItemTag) => {
                                     // console.log(checked, groupKey, groupIndex, mockItemTag);
                                     let oldMockDic = {...this.state.mockDic};

                                     const mockJsonValue = this.refs.centerView.mockValue();
                                     oldMockDic[groupKey][groupIndex]['data'] = mockJsonValue;
                                     oldMockDic[groupKey] = oldMockDic[groupKey].map(function (item, index) {
                                         const oldItem = {...item};
                                         if (index === groupIndex) {
                                             oldItem['checked'] = checked;
                                         } else {
                                             oldItem['checked'] = false;
                                         }
                                         return oldItem;
                                     });

                                     let oldCenterValue = {...this.state.centerValue};
                                     oldCenterValue['data'] = mockJsonValue;
                                     this.setState({
                                         mockDic: oldMockDic,
                                         centerValue: oldCenterValue
                                     });

                                     const mockObj = {
                                         mockKey: groupKey,
                                         mockValue: mockJsonValue,
                                         mockTag: mockItemTag
                                     };

                                     this.props.mockAction(mockObj, checked)
                                 }
                                 }
                                 onlyRowClick={(groupKey, groupIndex) => {
                                     console.log(this.state.mockDic[groupKey][groupIndex]);

                                     if (this.state.mockDic[groupKey][groupIndex] === undefined) {
                                         return;
                                     }

                                     const dic = {...this.state.mockDic};

                                     Object.keys(dic).map(function (itemKey) {
                                         dic[itemKey] = dic[itemKey].map(function (item) {
                                             item['disabled'] = true;
                                             return item;
                                         });
                                     });

                                     dic[groupKey][groupIndex]['disabled'] = false;

                                     this.setState({
                                         mockDic: dic,
                                         centerValue: dic[groupKey][groupIndex],
                                         addMockBtnDisabled: true,
                                         texareaReadonly: false,

                                         // defaultOpenKey:groupKey,
                                         defaultSelectedKey: groupKey + groupIndex

                                     })
                                 }}

                                 groupClick={(groupsKeys) => {

                                     console.log(groupsKeys);
                                     this.setState({openKey: groupsKeys});
                                 }
                                 }
                                 deleteAction={(groupKey,groupIndex) => {

                                     const dic = {...this.state.mockDic};
                                     console.log('deleteAction',this.state.mockDic,dic[groupKey]);
                                     dic[groupKey].splice(groupIndex,1);

                                     console.log('deleteAction333',dic[groupKey]);
                                     this.setState({
                                         mockDic: dic,
                                         centerValue: null,
                                         defaultSelectedKey:null
                                     })
                                 }
                                 }
                    />

                </Col>

                {/*中*/}
                <Col span={12}>
                    <CenterView
                        ref="centerView"
                        dataValue={this.state.centerValue}
                        mockClick={(mockItem) => {
                            console.log('需求mock的数据', mockItem);

                            if (mockItem === undefined ||
                                mockItem === null ||
                                mockItem.length === 0) {
                                ErrorModalAutoDismiss('没有mock数据');
                                return;
                            }
                            let oldMockDic = {...this.state.mockDic};
                            /**
                             * {
                             *  "path":[]
                             *  "path2":[]
                             * }
                             * */
                            if (oldMockDic[mockItem.config.urlIdentification] === undefined) {
                                oldMockDic[mockItem.config.urlIdentification] = [];
                            }

                            // 1.除了新加的mock其他的都不可编辑
                            Object.keys(oldMockDic).map(function (itemKey) {
                                oldMockDic[itemKey] = oldMockDic[itemKey].map(function (item) {
                                    item['disabled'] = true;
                                    return item;
                                });
                            });

                            //2. 新添加的默认选中 且可以勾选
                            mockItem['checked'] = false;
                            mockItem['disabled'] = false;
                            oldMockDic[mockItem.config.urlIdentification].push(mockItem);

                            const openKey = mockItem.config.urlIdentification;
                            let lastOpenkes = [...this.state.openKey];
                            lastOpenkes.push(openKey);
                            const dedupeKeys = this.dedupe(lastOpenkes);

                            console.log('3333', dedupeKeys);

                            const selectedKey = openKey + oldMockDic[mockItem.config.urlIdentification].indexOf(mockItem);
                            this.setState({
                                mockDic: oldMockDic,
                                addMockBtnDisabled: true,

                                openKey: dedupeKeys,
                                defaultSelectedKey: selectedKey,
                                texareaReadonly: false,
                            });

                        }}
                        btnDisabled={this.state.addMockBtnDisabled}
                        texareaReadonly={this.state.texareaReadonly}
                    />
                </Col>

                {/*右*/}
                <Col span={6}>
                    <RightView method={this.methodForRight()}
                               timeValue={this.timeForRight()}
                               currentText={this.currentTextForRight()}
                               segmentValue={this.state.otherInfoKey}
                               tabClick={(e) => {
                                   this.setState({otherInfoKey: e.target.value})
                               }}/>
                </Col>
            </Row>
        </div>
    }

    methodForRight = () => {
        try {
            return String(this.state.centerValue.config.method).toUpperCase();
        } catch (e) {
            return '';
        }
    };


    timeForRight = () => {
        try {
            Date.prototype.format = function (fmt) { //author: meizz
                var o = {
                    "M+": this.getMonth() + 1, //月份
                    "d+": this.getDate(), //日
                    "h+": this.getHours(), //小时
                    "m+": this.getMinutes(), //分
                    "s+": this.getSeconds(), //秒
                    "q+": Math.floor((this.getMonth() + 3) / 3), //季度
                    "S": this.getMilliseconds() //毫秒
                };
                if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
                for (var k in o)
                    if (new RegExp("(" + k + ")").test(fmt))
                        fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
                return fmt;
            }
            return new Date(parseInt(this.state.centerValue.config.timestamp)).format('yyyy-MM-dd hh:mm:ss');
        } catch (e) {
            return '';
        }
    };

    valueFix = (value) => {
        try {
            return jsonFormat(value, {
                type: 'space',
                size: 2
            });
        } catch (e) {
            return value;
        }

    };

    currentTextForRight = () => {
        try {
            if (this.state.otherInfoKey === 'headers') {
                return this.valueFix(this.state.centerValue.config[this.state.otherInfoKey])
            }
            if (this.state.otherInfoKey === 'data') {
                return this.valueFix(JSON.parse(this.state.centerValue.config[this.state.otherInfoKey]))
            }
            return this.state.centerValue.config[this.state.otherInfoKey];
        } catch (e) {
            return '';
        }
    }
}
